//
//  RZSlideMenuView.m
//  Doumi
//
//  Created by reyzhang on 2021/3/19.
//

#import "RZSlideMenuView.h"
#import "UIView+Helper.h"
#import "UIView+Frame.h"
#import <Masonry/Masonry.h>


@interface RZSlideMenuView () <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) RZSlideMenuConfig *config;
@property (nonatomic, strong) UIButton *coverBtn;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation RZSlideMenuView

- (instancetype)initWithConfig:(RZSlideMenuConfig *)config {
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
        self.config = config;
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    [self addSubview:self.coverBtn];
    [self addSubview:self.contentView];
    [self.contentView addSubview:self.tableView];
}


- (void)showWithAnimation:(BOOL)animation {
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    [window addSubview:self];
    self.coverBtn.frame = self.bounds;
    
    //初始化位置
    CGFloat posX = self.config.direction == DirectionFromLeft ? -self.config.contentWidth : self.width;
    self.contentView.frame = CGRectMake(posX, self.config.topMargin, self.config.contentWidth, self.config.cellHeight * self.menuArray.count);
    self.tableView.frame = self.contentView.bounds;
    
    //倒角
    UIRectCorner corner = self.config.direction == DirectionFromLeft ? UIRectCornerTopRight|UIRectCornerBottomLeft|UIRectCornerBottomRight :
    UIRectCornerTopLeft|UIRectCornerBottomLeft|UIRectCornerBottomRight;
    [self.contentView addRoundingCorners:corner cornerRadii:CGSizeMake(10, 10)];
    
    //弹性动画
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.coverBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        
        CGFloat posX = self.config.direction == DirectionFromLeft ? self.contentView.width + self.config.leftMargin : self.width - self.contentView.width - self.config.rightMargin;
        [self.contentView setLeft:posX];
    } completion:^(BOOL finished) {
        self->_isShow = YES;
    }];
}

- (void)hideWithAnimation:(BOOL)animation {
    [UIView animateWithDuration:0.1 animations:^{
        self.coverBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
        CGFloat posX = self.config.direction == DirectionFromLeft ? - self.contentView.width : self.width;
        [self.contentView setLeft:posX];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self->_isShow = NO;
    }];
}

- (void)setMenuArray:(NSArray<RZSlideMenuModel *> *)menuArray {
    _menuArray = menuArray;
    [self.tableView reloadData];
}

- (void)closeMenu:(id)sender {
    [self hideWithAnimation:YES];
}

#pragma mark - UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.menuArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RZSlideMenuTableCell *cell = [tableView dequeueReusableCellWithIdentifier:[RZSlideMenuTableCell identifier] forIndexPath:indexPath];
    RZSlideMenuModel *model = self.menuArray[indexPath.row];
    cell.menuModel = model;
    if (indexPath.row < self.menuArray.count) {
        CGFloat posX = model.icon.length > 0 ? 24 : 0;
//        [cell drawBottomLineFromX:posX isEnd:YES];
        [cell drawLineWithRect:CGRectMake(posX, 45.5, self.contentView.width, 1)];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.config.cellHeight;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RZSlideMenuModel *model = self.menuArray[indexPath.row];
    [self hideWithAnimation:YES];
    !self.selectMenuAtIndex ?: self.selectMenuAtIndex(indexPath.row, model);
}
#pragma mark Lazy

- (UIButton *)coverBtn {
    if (!_coverBtn) {
        _coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _coverBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        [_coverBtn addTarget:self action:@selector(closeMenu:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _coverBtn;
}


- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor whiteColor];
    }
    return _contentView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[RZSlideMenuTableCell class] forCellReuseIdentifier:[RZSlideMenuTableCell identifier]];
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}


@end



#pragma mark ============RZSlideMenuConfig===========
@implementation RZSlideMenuConfig

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.direction = DirectionFromRight;
    self.leftMargin = 20;
    self.rightMargin = 20;
    if (@available(iOS 11.0, *)) {
        CGFloat top = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top == 0 ? 0 : 20;
        self.topMargin = 64 +[UIApplication sharedApplication].delegate.window.safeAreaInsets.top - top - 5;
    } else {
        self.topMargin = 64 - 5;
    }
    self.contentWidth = 153;
    self.cellHeight = 46;
}

@end

#pragma mark ============RZSlideMenuModel===========
@implementation RZSlideMenuModel

+ (instancetype)createWithIcon:(NSString *)icon name:(NSString *)name {
    RZSlideMenuModel *model = [[RZSlideMenuModel alloc] init];
    model.icon = icon;
    model.name = name;
    return model;
}
@end

#pragma mark ============RZSlideMenuTableCell===========

@interface RZSlideMenuTableCell ()
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation RZSlideMenuTableCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    [self.contentView addSubview:self.iconImageView];
    [self.contentView addSubview:self.titleLabel];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(22);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.contentView);
        make.left.mas_equalTo(self.iconImageView.mas_right).mas_offset(13);
    }];
    
    
    
}


- (void)setMenuModel:(RZSlideMenuModel *)model {
    if (model.icon.length > 0) {
        self.iconImageView.hidden = NO;
        self.iconImageView.image = [UIImage imageNamed:model.icon];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.iconImageView.mas_right).mas_offset(13);
        }];
    }else {
        self.iconImageView.hidden = YES;
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(17);
        }];
    }
        
    self.titleLabel.text = model.name;

    
}

- (UIImageView *)iconImageView {
    if (!_iconImageView) {
        _iconImageView = [[UIImageView alloc] init];
    }
    return _iconImageView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:14];
        _titleLabel.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
    }
    return _titleLabel;
}

@end
